package cn.com.pajx.pajx_visitor_v3.ui.activity;

import android.annotation.SuppressLint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.pajx.facelibrary.utils.DensityUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.ChooseIntervieweeFragment;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.ChooseTimeFragment;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.FaceGatherFragment;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.BaseImageUtils;
import cn.com.pajx.pajx_visitor_v3.utils.CornerTransform;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;
import cn.com.pajx.pajx_visitor_v3.utils.ToastUtil;
import id.zelory.compressor.Compressor;

/**
 * 新建拜访页面
 */
@SuppressLint("NonConstantResourceId")
public class NewVisiteActivity extends BaseMvpActivity<LoadDataPresenterImpl> {

    @BindView(R.id.view_visite_name)
    EditText viewName;
    @BindView(R.id.view_visite_phone)
    EditText viewPhone;
    @BindView(R.id.view_id_card)
    EditText viewIdCard;
    @BindView(R.id.tv_visite_time)
    TextView tvVisiteTime;
    @BindView(R.id.tv_visite_object)
    TextView tvVisiteObject;
    @BindView(R.id.view_cause)
    EditText viewCause;
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    private EditText[] editTexts;

    private String img_no, photo_path, visitor_name, visitor_phone, visitor_id_card;
    private String interviewee_id, interviewee_name, interview_time, interview_cause;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_visite;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected void initView() {
        setHeadTitle("新建拜访");
        EventBus.getDefault().register(this);
        initDownTimer();
        //EditText事件监听
        initEditView();
    }

    /**
     * 隐藏系统软键盘
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initEditView() {
        editTexts = new EditText[]{viewName, viewPhone, viewIdCard, viewCause};
        for (int i = 0; i < editTexts.length; i++) {
            int index = i;
            EditText viewInput = editTexts[index];
            viewInput.setOnTouchListener((view, motionEvent) -> {
                resetDownTimer();
                return false;
            });
            viewInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    resetDownTimer();
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
        }
    }


    @OnClick({R.id.view_photo, R.id.view_time, R.id.view_object, R.id.tv_submit})
    public void onClickViewed(View view) {
        cancelDownTimer();
        switch (view.getId()) {
            case R.id.view_photo://图像
                FaceGatherFragment faceGatherFragment = FaceGatherFragment.newInstance();
                faceGatherFragment.show(getSupportFragmentManager(), "faceGatherFragment");
                faceGatherFragment.setOnFunctionListener(img_path -> {
                    photo_path = img_path;
                    LogUtils.e("img_path=" + img_path);
                    File photoFile = new File(photo_path);
                    if (photoFile.exists()) {
                        uploadPhotoToServer(photoFile);
                    } else {
                        ToastUtil.toast("照片文件不存在");
                    }
                });
                break;
            case R.id.view_time://时间
                ChooseTimeFragment chooseTimeFragment = ChooseTimeFragment.newInstance();
                chooseTimeFragment.show(getSupportFragmentManager(), "chooseTimeFragment");
                chooseTimeFragment.setOnFunctionListener((show_time, time) -> {
                    LogUtils.e("time=" + time);
                    interview_time = time;
                    tvVisiteTime.setText(show_time);
                });
                break;
            case R.id.view_object://对象
                ChooseIntervieweeFragment intervieweeFragment = ChooseIntervieweeFragment.newInstance();
                intervieweeFragment.show(getSupportFragmentManager(), "intervieweeFragment");
                intervieweeFragment.setOnFunctionListener(bean -> {
                    interviewee_name = bean.getUser_name();
                    interviewee_id = bean.getUser_id();
                    tvVisiteObject.setText(bean.getUser_name());
                    LogUtils.e("tea_name=" + interviewee_name);
                    LogUtils.e("tea_phone=" + bean.getUser_phone());
                });
                break;
            case R.id.tv_submit://提交申请
                visitor_name = viewName.getText().toString().trim();
                visitor_phone = viewPhone.getText().toString().trim();
                visitor_id_card = viewIdCard.getText().toString().trim();
                interview_cause = viewCause.getText().toString().trim();
                LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
                paramsMap.put("vis_photo", img_no);
                paramsMap.put("vis_name", visitor_name);
                paramsMap.put("vis_phone", visitor_phone);
                paramsMap.put("vis_idcard", visitor_id_card);
                paramsMap.put("user_id", interviewee_id);
                paramsMap.put("user_name", interviewee_name);
                paramsMap.put("time_plan", interview_time);
                paramsMap.put("vis_note", interview_cause);
                mPresenter.loadData(Api.NEW_VISITE, paramsMap, "NEW_VISITE", "努力加载中");
                break;
        }
    }

    private void showPhotoView() {
        CornerTransform transform = new CornerTransform(mContext, DensityUtil.dp2px(mContext, 8));
        transform.setCornerRadius(false, false, false, false);
        BaseImageUtils.setFileCornerImage(mContext, ivPhoto, new File(photo_path), transform);
    }

    private void uploadPhotoToServer(File photoFile) {
        LogUtils.e("photoFile.length=" + photoFile.length());
        //大于500kb再压缩
        if (photoFile.length() > 500000) {
            try {
                Compressor compressor = new Compressor(mContext);
                compressor.setQuality(100);
                photoFile = compressor.compressToFile(photoFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("type", "1");
        mPresenter.upLoadFile(Api.UPLOAD_FILE, photoFile, paramsMap, "UPLOAD_FILE", "正在上传");
    }

    @Override
    public void onSuccess(String data, String aesKey, String message, int code, String tag) {
        super.onSuccess(data, aesKey, message, code, tag);
        if (TextUtils.equals(tag, "UPLOAD_FILE")) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                img_no = jsonObject.getString("img_no");
                LogUtils.e("img_no=" + img_no);
                showPhotoView();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            EventBus.getDefault().post(new EventMessage(AppConstant.NEW_VISITE));
            skip2Success("0");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        if (TextUtils.equals(AppConstant.FRAGMENTDIALOG_DISMISS, bean.getMessage())) {
            resetDownTimer();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}